<?php
/**
 * Shop_Model_Order
 * 
 * @version $Id$
 * @author $Author$
 */
class Shop_Model_Order extends Promotor_Model_Scaffold {

	protected $_dbTableClass = 'Shop_Model_DbTable_Order';
	
	protected $_cachedMethods = array();
	
	/**
	 * @return Zend_Db_Table_Row_Abstract|null
	 */
	public function updateStatusSuccess($sessionId)
	{
		$table = $this->getDbTable();
		$select = $table->select()->where('session_id = ?', $sessionId);
		
		try {
			$row = $table->fetchRow($select);
		} catch(Zend_Db_Exception $e) {
			$this->_setStatus(self::FAILURE);
			$this->_addException($e);
			$row = null;
		}
			
		
		if (!($row instanceof Zend_Db_Table_Row))
		{
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('Shop_Model_Order::updateStatus ');
			return;
		}

		$row->status = 99;
		
		try {
			$row->save();
			$this->_setStatus(self::SUCCESS);
		} catch(Zend_Db_Exception $e) {
			$this->_setStatus(self::FAILURE);
			$this->_addException($e);
		}
		
		return $row;
	}
	
	/**
	 * 
	 */
	public function updateStatus(KontorX_Payments_Platnosci_Response_Online $response)
	{
		$sessionId = $response->getSessionId();
		$row = $this->findBy('session_id', $sessionId);
		
		if (!$row instanceof Zend_Db_Table_Row_Abstract)
		{
			$this->_setStatus(self::FAILURE);
			$this->_addMessage('Shop_Model_Order::updateStatus ');
			return;
		}
		
		// TODO: Send notification
	}
	
	/**
	 * @return mixed
	 */
	public function add(array $data, $amount, $sessionId = null, $info = null, $email)
	{
		$table = $this->getDbTable();
		
		if (null === $sessionId)
		{
			if (!Zend_Session::isStarted())
			{
				Zend_Session::start();
			}
			$sessionId = Zend_Session::getId();
		}

		$newData = array(
			'session_id' => $sessionId,
			'status' => 1, //Nowa (w platnosci.pl)
			'amount' => $amount,
			'date' => date('Y-m-d H:i:s'),
			'username' => $data['fullname'],
			'email' => $email,
			'info' => $info
		);
		
		$row = $table->createRow($newData);

		try {
			$result = $row->save();
			$this->_setStatus(self::SUCCESS);
			return $result;
		} catch (Zend_Db_Table_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
		}
	}
}